<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Http;

/**
 * 拼多多
 */
class Pdd extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 授权，仅自己使用
     * https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.rp.prom.url.generate
     */
    public function authorization()
    {
        $params = array(
            'type'              => 'pdd.ddk.rp.prom.url.generate',
            'channel_type'      => 10,
            'client_id'         => config('pdd.ClientId'),
            'timestamp'         => time(),
            'p_id_list'         => json_encode([config('pdd.Pid')], true),
            'custom_parameters' => json_encode(['uid' => 999], true)
        );
        $params['sign'] = $this->getSign($params, config('pdd.ClientSecret'));
        $result = Http::post('https://gw-api.pinduoduo.com/api/router', json_encode($params));
        $result = json_decode($result, true);
        $this->success('', $result);
    }

    /**
     * 查询是否绑定备案，仅自己使用
     * https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.member.authority.query
     */
    public function authorizationQuery()
    {
        $params = array(
            'type'      => 'pdd.ddk.member.authority.query',
            'client_id' => config('pdd.ClientId'),
            'timestamp' => time(),
            'pid'       => config('pdd.Pid'),
        );

        $params['sign'] = $this->getSign($params, config('pdd.ClientSecret'));
        $result = Http::post('https://gw-api.pinduoduo.com/api/router', json_encode($params));
        $result = json_decode($result, true);
        $this->success('', $result);
    }

    /**
     * 为已授权的用户开通消息服务
     * https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.member.authority.query
     * code获取链接：https://jinbao.pinduoduo.com/open.html?response_type=code&client_id=913427bdc311417caad37492af64678e&redirect_uri=https://wawa.yun-ling.cn/api/pdd/notifyx
     */
    public function authorizationNotify()
    {
        $params = array(
            'type'      => 'pdd.pop.auth.token.create',
            'client_id' => config('pdd.ClientId'),
            'timestamp' => time(),
            'code'      => '7215f0eddf1649da8097368bc71e42a3788613d4'
        );

        $params['sign'] = $this->getSign($params, config('pdd.ClientSecret'));
        $result = Http::post('https://gw-api.pinduoduo.com/api/router', json_encode($params));
        $result = json_decode($result, true);
        if (isset($result['pop_auth_token_create_response'])) {
            $tokenParams = array(
                'type'         => 'pdd.pmc.user.permit',
                'client_id'    => config('pdd.ClientId'),
                'timestamp'    => time(),
                'access_token' => $result['pop_auth_token_create_response']['access_token']
            );

            $tokenParams['sign'] = $this->getSign($tokenParams, config('pdd.ClientSecret'));
            $tokenResult = Http::post('https://gw-api.pinduoduo.com/api/router', json_encode($tokenParams));
            $tokenResult = json_decode($tokenResult, true);
            $this->success('', $tokenResult);
        } else {
            $this->error('access_token获取失败', $result);
        }
    }

    /**
     * 多多进宝商品推荐API
     * https://jinbao.pinduoduo.com/third-party/rank
     */
    public function recommend()
    {
        $params = array(
            'type' => 'pdd.ddk.goods.recommend.get',
        );
        $this->common($params);
    }

    /**
     * 多多进宝推广链接生成
     * https://open.pinduoduo.com/application/document/api?id=pdd.ddk.goods.promotion.url.generate
     */
    public function generate($goodsSign)
    {
        $customParameters = [
            'uid' => 999,
            'pid' => 888
        ];
        $params = array(
            'type'                     => 'pdd.ddk.goods.promotion.url.generate',
            'custom_parameters'        => json_encode($customParameters, true),
            'p_id'                     => config('pdd.Pid'),
            'goods_gen_url_param_list' => json_encode([['goods_sign' => $goodsSign]], true)
        );
        $this->common($params);
    }

    public function common($params)
    {
        $params['client_id'] = config('pdd.ClientId');
        $params['timestamp'] = time();
        $params['sign'] = $this->getSign($params, config('pdd.ClientSecret'));
        $result = Http::post('https://gw-api.pinduoduo.com/api/router', json_encode($params));
        $result = json_decode($result, true);
        if (isset($result['error_response']))
            $this->error($result['error_response']['error_msg'], $result['error_response'], $result['error_response']['error_code']);
        else
            $this->success('返回成功', $result);
    }


    /**
     * 通知回调
     */
    function notifyx()
    {
        return "success";
    }

    /**
     * 按首字母升序排列（ASCII ASC） 并 无缝拼接字符串
     */
    private function getSign($params, $client_secret)
    {
        if (is_array($params)) {
            ksort($params);
            $paramsStr = '';
            array_walk($params, function ($item, $key) use (&$paramsStr) {
                $paramsStr .= sprintf('%s%s', $key, $item);
            });
            $sign = strtoupper(md5($client_secret . $paramsStr . $client_secret));
            return $sign;
        } else {
            return "";
        }
    }
}
